package com.suse.ecommerce.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.suse.ecommerce.pojo.*;
import com.suse.ecommerce.service.OrderItemService;
import com.suse.ecommerce.service.OrderService;
import com.suse.ecommerce.service.ShoppingService;
import com.suse.ecommerce.uilts.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.sql.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class OrderController {
    @Autowired
    private ShoppingService shoppingService;
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;


    @RequestMapping("/auth/submitOrder")
    public Object submitOrder(@SessionAttribute("user")User user, long addressId, HttpServletResponse response){
        //获取购物车中的商品
        List<Shopping> shoppings = shoppingService.queryShopping(user.getUserId());
        long totalPrice=0;
        Integer totalNum=0;
        //生成订单号
        String out_trade_no= UUID.randomUUID().toString().substring(0, 18);
        List<OrderProduct> orderProducts=new ArrayList<>();
        OrderProduct orderProduct=new OrderProduct();
        //计算商品价格
        for (Shopping shopping:shoppings) {
            totalPrice+=shopping.getOnePrice()*shopping.getNum();
            totalNum+=shopping.getNum();
            orderProduct.set(null,shopping.getProductId(),shopping.getTitle(),shopping.getNum(),shopping.getOnePrice()
            ,shopping.getOnePrice()*shopping.getNum(),out_trade_no);
            //向订单项中插入记录
            orderProducts.add(orderProduct);

            Shopping shopping1=new Shopping();
            shopping1.setUserId(user.getUserId());
            shopping1.setShoppingId(shopping.getShoppingId());
            //购物车中的商品
            shoppingService.delShopping(shopping1);
        }
        //生成订单
        Order order=new Order(out_trade_no,0,new Date(new java.util.Date().getTime()),totalPrice,totalNum,totalPrice,"支付宝",0l,
                null,null,null,null,null,user.getUserId(),addressId);
        //插入订单
        orderService.addOrder(order);

        //插入订单项
        for (OrderProduct orderProduct1:orderProducts) {
            orderItemService.addOrderItems(orderProduct1);
        }
        //向支付宝发送请求
        //向支付宝发起支付请求
        String subject="川理电商";
        String total_amount=totalPrice/100+"";
        String body="";
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        try {
            String	 result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=" + AlipayConfig.charset);
            response.getWriter().write(result);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询订单
     */
    @RequestMapping("/order/queryOrder")
    @ResponseBody
    public Msg queryOrder(Order order, @RequestParam(value = "pn",defaultValue = "1")int pn){
        PageInfo<Order> list = orderService.queryOrder(order,pn);
        return Msg.success("order").add("orders",list);
    }

    @RequestMapping("/order/confirmOrder")
    @ResponseBody
    public Msg confirmOrder(Order order){
        if(order.getOrderId() == null){
            return Msg.error("没有id");
        }else{
            orderService.updateOrderStatusById(order);
            return Msg.success("更新成功");
        }
    }
}
